// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.UserControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.RiskService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.AuthZService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.NotificationsService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;
using Microsoft.Security.Application;
using System.Collections.Generic;

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks
{
    public partial class CreateTasks : System.Web.UI.UserControl
    {
        List<Task> lstTasks = new List<Task>();
        List<Group> lstGroups = null;
        List<Category> lstCategories = null;
        List<Microsoft.InformationSecurity.CISF.Security.AuthZServices.User> lstUsers = null;
        List<TaskStatus> lstStatus = null;
        int defaultNotificationScheduleID = 0;
        bool isTTaskUser = false;
        bool isTaskManager = false;
        public int RiskID
        {
            set { ViewState["RiskID"] = value; }
            get
            {
                if (ViewState["RiskID"] != null)
                    return (int)ViewState["RiskID"];
                else
                    return 0;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            isTTaskUser = this.Context.User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser"));
            isTaskManager = this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager"));

            if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskUser")))
            {
                this.LoadData();
            }

        }

        public void LoadData()
        {
            if (RiskID > 0)
            {
                TasksServiceClient tasksClient = new TasksServiceClient();
                if (ViewState["Groups"] == null)
                {
                    lstStatus = new List<TaskStatus>();
                    lstStatus.AddRange(tasksClient.GetAllTaskStatus());
                    lstGroups = new List<Group>();
                    lstGroups.AddRange(tasksClient.GetActiveGroups());
                    lstCategories = new List<Category>();
                    lstCategories.AddRange(tasksClient.GetActiveCategories());
                    lstUsers = new List<Microsoft.InformationSecurity.CISF.Security.AuthZServices.User>();
                    if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser")))
                    {
                        AuthZServiceClient objClient = new AuthZServiceClient();
                        lstUsers.AddRange(objClient.GetUsersInRole("Task User"));
                        objClient.Close();
                    }
                    else
                    {
                        //Microsoft.InformationSecurity.CISF.Security.AuthZServices.User usr = new Microsoft.InformationSecurity.CISF.Security.AuthZServices.User(((CISF.Security.Principal.CISFIdentity)this.Page.User.Identity).PersonId, ((CISF.Security.Principal.CISFIdentity)this.Page.User.Identity).FullName, this.Page.User.Identity.Name, ((CISF.Security.Principal.CISFIdentity)this.Page.User.Identity).FullName, 0, "", null);
                        //lstUsers.Add(usr);
                        Microsoft.InformationSecurity.CISF.Security.AuthZServices.User usr = new Microsoft.InformationSecurity.CISF.Security.AuthZServices.User();
                        usr.PersonId = ((CISF.Security.Principal.CISFIdentity)this.Page.User.Identity).PersonId;
                        usr.FullName = ((CISF.Security.Principal.CISFIdentity)this.Page.User.Identity).FullName;
                        lstUsers.Add(usr);
                    }
                    lstUsers.Sort(new UserComparer());

                    NotificationsService.NotificationsServiceClient notClient = new NotificationsServiceClient();
                    defaultNotificationScheduleID = notClient.GetDefaultNotificationSchedule();
                    notClient.Close();
                    ViewState["DefaultNotificationScheduleID"] = defaultNotificationScheduleID;
                    ViewState["Status"] = lstStatus;
                    ViewState["Groups"] = lstGroups;
                    ViewState["Categories"] = lstCategories;
                    ViewState["Users"] = lstUsers;


                }
                else
                {
                    lstStatus = (List<TaskStatus>)ViewState["Status"];
                    lstGroups = (List<Group>)ViewState["Groups"];
                    lstCategories = (List<Category>)ViewState["Categories"];
                    lstUsers = (List<Microsoft.InformationSecurity.CISF.Security.AuthZServices.User>)ViewState["Users"];
                    defaultNotificationScheduleID = (int)ViewState["DefaultNotificationScheduleID"];
                }

                if (ViewState["Tasks"] == null)
                {
                    lstTasks = new List<Task>();
                    if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser")))
                        lstTasks.AddRange(tasksClient.GetTasks(RiskID));
                    else
                        lstTasks.AddRange(tasksClient.GetTasksByUser(RiskID, ((CISF.Security.Principal.CISFIdentity)this.Page.User.Identity).PersonId));
                    tasksClient.Close();

                    ViewState["Tasks"] = lstTasks;
                }
                else
                {
                    lstTasks = (List<Task>)ViewState["Tasks"];
                }

                if (!Page.IsPostBack)
                    this.DoDataBind();

                tasksClient.Close();

            }

            if (gridTasks.Rows.Count == 0)
                btnSave.Visible = false;
            else
                btnSave.Visible = true;
        }

        public void DoDataBind()
        {
            this.DoDataBind(true);
        }
        public void DoDataBind(bool addTask)
        {
            this.DoDataBind(addTask, false);
        }
        public void DoDataBind(bool addTask, bool isEditingExistingTask)
        {

            //checking and deleteing if the last task is emtpy 
            if (lstTasks.Count > 0 && string.IsNullOrEmpty(lstTasks[lstTasks.Count - 1].Name))
                lstTasks.Remove(lstTasks[lstTasks.Count - 1]);

            bool blnAddAccess = (addTask && (this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager"))));
            if (blnAddAccess)
            {
                Task t = new Task();
                t.AssignedTo = new Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService.User();
                t.Group = new Group();
                t.Category = new Category();
                t.Status = new TaskStatus();
                t.NotificationSchedule = new Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService.NotificationSchedule();
                t.DueDate = DateTime.Now.AddDays(7);
                t.CreatedBy = Utility.GetUserFullName();
                t.CreatedDate = DateTime.UtcNow;
                lstTasks.Add(t);
                ViewState["Tasks"] = lstTasks;
                gridTasks.EditIndex = lstTasks.Count - 1;
            }

            gridTasks.DataSource = lstTasks;

            gridTasks.Columns[7].Visible = true;
            gridTasks.DataBind();
            gridTasks.Columns[7].Visible = false;

            if (gridTasks.Rows.Count == 0)
                btnSave.Visible = false;
            else
                btnSave.Visible = true;
            if (gridTasks.EditIndex >= 0 && gridTasks.EditIndex < gridTasks.Rows.Count)
            {
                LinkButton c = (LinkButton)gridTasks.Rows[gridTasks.EditIndex].Cells[0].FindControl("btnAdd");

                if (c != null)
                {
                    if (isEditingExistingTask)
                    {
                        c.Text = "Save";
                        LinkButton c1 = (LinkButton)gridTasks.Rows[gridTasks.EditIndex].Cells[0].FindControl("btnCancel");
                        if (c1 != null)
                            c1.Visible = true;
                    }
                    else
                    {
                        c.Text = "Add";
                    }
                }
            }
            this.HideDeleteButton();
        }

        protected void gridTasks_RowEditing(object sender, GridViewEditEventArgs e)
        {
            if (e.NewEditIndex >= 0)
            {
                gridTasks.EditIndex = e.NewEditIndex;
                this.DoDataBind(false, true);
            }

        }
        protected void gridTasks_RowCancellingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridTasks.EditIndex = -1;
            this.DoDataBind(true);
        }
        protected void gridTasks_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DropDownList ddlAssignedTo = (DropDownList)e.Row.Cells[1].FindControl("ddlAssignedTo");
                DropDownList ddlStatus = (DropDownList)e.Row.Cells[3].FindControl("ddlStatus");
                DropDownList ddlCategory = (DropDownList)e.Row.Cells[4].FindControl("ddlCategory");
                DropDownList ddlGroup = (DropDownList)e.Row.Cells[5].FindControl("ddlGroup");

                if (lstUsers != null && ddlAssignedTo != null)
                {
                    IOrderedEnumerable<Microsoft.InformationSecurity.CISF.Security.AuthZServices.User> lstOrderedUsers = lstUsers.OrderBy(eachUser => eachUser.FullName);

                    ddlAssignedTo.DataTextField = "FullName";
                    ddlAssignedTo.DataValueField = "PersonId";
                    //ddlAssignedTo.DataSource = lstUsers;
                    ddlAssignedTo.DataSource = lstOrderedUsers;
                    ddlAssignedTo.DataBind();
                    ddlAssignedTo.Items.Insert(0, new ListItem("", ""));
                }

                if (lstCategories != null && ddlCategory != null)
                {
                    ddlCategory.DataTextField = "Name";
                    ddlCategory.DataValueField = "ID";
                    ddlCategory.DataSource = lstCategories;
                    ddlCategory.DataBind();
                    ddlCategory.Items.Insert(0, new ListItem("", ""));
                }

                if (lstGroups != null && ddlGroup != null)
                {
                    ddlGroup.DataTextField = "Name";
                    ddlGroup.DataValueField = "ID";
                    ddlGroup.DataSource = lstGroups;
                    ddlGroup.DataBind();
                    ddlGroup.Items.Insert(0, new ListItem("", ""));
                }

                if (lstStatus != null && ddlStatus != null)
                {
                    ddlStatus.DataTextField = "Name";
                    ddlStatus.DataValueField = "ID";
                    ddlStatus.DataSource = lstStatus;
                    ddlStatus.DataBind();
                }


                if (e.Row.DataItem is Task)
                {
                    Task t = (Task)e.Row.DataItem;
                    if (ddlAssignedTo != null && t.AssignedTo.ID > 0 && ddlAssignedTo.Items.FindByValue(t.AssignedTo.ID.ToString()) != null)
                        ddlAssignedTo.Items.FindByValue(t.AssignedTo.ID.ToString()).Selected = true;

                    if (ddlCategory != null && t.Category.ID > 0 && ddlCategory.Items.FindByValue(t.Category.ID.ToString()) != null)
                        ddlCategory.Items.FindByValue(t.Category.ID.ToString()).Selected = true;

                    if (ddlGroup != null && t.Group.ID > 0 && ddlGroup.Items.FindByValue(t.Group.ID.ToString()) != null)
                        ddlGroup.Items.FindByValue(t.Group.ID.ToString()).Selected = true;

                    if (ddlStatus != null && t.Status.ID > 0 && ddlStatus.Items.FindByValue(t.Status.ID.ToString()) != null)
                        ddlStatus.Items.FindByValue(t.Status.ID.ToString()).Selected = true;

                    if (!isTaskManager)
                    {
                        if (!isTTaskUser)
                        {
                            if (e.Row.Cells[0].FindControl("btnEdit") != null)
                                e.Row.Cells[0].FindControl("btnEdit").Visible = false;
                        }
                        else
                        {
                            if (((CISF.Security.Principal.CISFIdentity)this.Context.User.Identity).PersonId != t.AssignedTo.ID)
                            {
                                if (e.Row.Cells[0].FindControl("btnEdit") != null)
                                    e.Row.Cells[0].FindControl("btnEdit").Visible = false;
                            }
                            else
                            {
                                if (e.Row.Cells[2].FindControl("ddlAssignedTo") != null)
                                {
                                    ((DropDownList)e.Row.Cells[2].FindControl("ddlAssignedTo")).Enabled = false;
                                }

                                if (e.Row.Cells[3].FindControl("txtDueDate") != null)
                                {
                                    ((TextBox)e.Row.Cells[3].FindControl("txtDueDate")).Enabled = false;
                                    ((AjaxControlToolkit.CalendarExtender)e.Row.Cells[3].FindControl("dueDateCalendar")).Enabled = false;
                                }

                            }
                        }
                    }
                }
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (defaultNotificationScheduleID <= 0)
            {
                Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_NO_DEFAULT"));
                return;
            }

            TextBox txtName = (TextBox)gridTasks.Rows[gridTasks.EditIndex].Cells[0].FindControl("txtName");
            DropDownList ddlAssignedTo = (DropDownList)gridTasks.Rows[gridTasks.EditIndex].Cells[1].FindControl("ddlAssignedTo");
            TextBox txtDueDate = (TextBox)gridTasks.Rows[gridTasks.EditIndex].Cells[2].FindControl("txtDueDate");
            DropDownList ddlStatus = (DropDownList)gridTasks.Rows[gridTasks.EditIndex].Cells[3].FindControl("ddlStatus");
            DropDownList ddlCategory = (DropDownList)gridTasks.Rows[gridTasks.EditIndex].Cells[4].FindControl("ddlCategory");
            DropDownList ddlGroup = (DropDownList)gridTasks.Rows[gridTasks.EditIndex].Cells[5].FindControl("ddlGroup");


            if (string.IsNullOrEmpty(txtName.Text))
            {
                Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_TITLE_REQ"), "Error", true);
                return;
            }
            foreach (Task t1 in lstTasks)
            {
                if (t1.Name == txtName.Text && lstTasks.IndexOf(t1) != gridTasks.EditIndex)
                {
                    Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_EXISTS"), "Error", true);
                    return;
                }
            }

            Task t = lstTasks[gridTasks.EditIndex];
            if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
            {
                DateTime dtNewDueDate;
                DateTime.TryParse(txtDueDate.Text, out dtNewDueDate);
                DateTime currentDate = DateTime.Parse(DateTime.Now.ToString("MM/dd/yyyy"));
                if (dtNewDueDate.Subtract(currentDate).Days < 0)
                {
                    Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_DUEDATE_NOTVALID"), "Error", true);
                    txtDueDate.Text = currentDate.ToString("MM/dd/yyyy");
                    return;
                }
                t.AssignedTo = new Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService.User();
                t.AssignedTo.ID = int.Parse(ddlAssignedTo.SelectedValue);
                t.AssignedTo.Name = ddlAssignedTo.SelectedItem.Text;
                t.DueDate = DateTime.Parse(txtDueDate.Text);
            }
            t.Name = txtName.Text;
            t.Description = "";
            t.Category = new Category();
            t.Category.ID = int.Parse(ddlCategory.SelectedValue);
            t.Category.Name = ddlCategory.SelectedItem.Text;
            t.Group = new Group();
            t.Group.ID = int.Parse(ddlGroup.SelectedValue);
            t.Group.Name = ddlGroup.SelectedItem.Text;
            t.LastUpdatedBy = Utility.GetUserFullName();
            t.LastUpdatedDate = DateTime.UtcNow;
            t.BusinessObject = new BusinessObject();
            t.BusinessObject.ID = RiskID;
            t.Status.ID = int.Parse(ddlStatus.SelectedValue);
            t.Status.Name = ddlStatus.SelectedItem.Text;
            t.NotificationSchedule = new Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService.NotificationSchedule();
            t.NotificationSchedule.ID = defaultNotificationScheduleID;
            t.PersonID = ((CISF.Security.Principal.CISFIdentity)Context.User.Identity).PersonId;
            if (lstTasks.Count > 0)
                lstTasks[gridTasks.EditIndex] = t;
            else
                lstTasks[0] = t;


            btnSave.Enabled = true;
            gridTasks.EditIndex = -1;
            this.DoDataBind();
        }

        protected void gridTasks_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                lstTasks.Remove(lstTasks[e.RowIndex]);
                if (this.GetNewTasksFromGrid(0).Count > 0)
                    btnSave.Enabled = true;
                else
                    btnSave.Enabled = false;

                this.DoDataBind(true);
            }
        }

        private List<Task> GetNewTasksFromGrid(int lastCount)
        {
            List<Task> newTasks = new List<Task>();
            //Looping through all tasks. Except the last one.
            for (int i = 0; i < lstTasks.Count - lastCount; i++)
            {
                Task t = lstTasks[i];
                if (t.ID <= 0)
                {
                    newTasks.Add(t);
                }
            }
            return newTasks;
        }

        private List<Task> GetOldTasksFromGrid(int lastCount)
        {
            List<Task> newTasks = new List<Task>();
            //Looping through all tasks. Except the last one.
            for (int i = 0; i < lstTasks.Count - lastCount; i++)
            {
                Task t = lstTasks[i];
                if (t.ID > 0)
                {
                    newTasks.Add(t);
                }
            }
            return newTasks;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (defaultNotificationScheduleID <= 0)
            {
                Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "SCHED_NO_DEFAULT"));
                return;
            }
            TasksServiceClient tasksClient = new TasksServiceClient();
            try
            {
                List<Task> newTasks = this.GetNewTasksFromGrid(1);
                tasksClient.AddTasks(newTasks.ToArray());
                newTasks = this.GetOldTasksFromGrid(1);
                foreach (Task t in newTasks)
                {
                    t.PersonID = ((CISF.Security.Principal.CISFIdentity)Context.User.Identity).PersonId;
                    tasksClient.UpdateTask(t);
                }
                lstTasks.Clear();
                lstTasks.AddRange(tasksClient.GetTasks(RiskID));
                gridTasks.EditIndex = -1;
                this.DoDataBind();
                tasksClient.Close();
                Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASKS_SAVED"));
            }
            catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
            {
                if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                {
                    Utility.ShowMessage(this.Page.Master, fex.Message.ToString(), "Error", true);
                }
                else
                    Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASKS_SAVE_UNKWNERR"), "Error", true);
            }
            catch
            {
                Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASKS_SAVE_UNKWNERR"), "Error", true);
            }
            tasksClient.Close();
        }

        private void HideDeleteButton()
        {
            foreach (GridViewRow gvr in gridTasks.Rows)
            {
                int taskID = int.Parse(gvr.Cells[7].Text);
                if (taskID > 0)
                {
                    LinkButton btnDelete = (LinkButton)gvr.Cells[0].FindControl("btnDelete");
                    if (btnDelete != null)
                        btnDelete.Visible = false;
                }
            }
        }

    }
}
